﻿using AntdUI;
using CKS.Core.Framework;
using CKS.MES.Server.Models;
using CKS.MES.Server.UserControls;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.ComponentModel.Design.ObjectSelectorEditor;

namespace CKS.MES.Server
{
    public partial class MainForm : AntdUI.BaseForm
    {
        public MainForm()
        {
            InitializeComponent();

            this.Text = "DI上位机系统";
            windowBar1.Text = this.Text;
            windowBar1.SubText = "锴士";


            this.FormBorderStyle = FormBorderStyle.None;
            //WindowState = FormWindowState.Maximized;
            ////// 重设窗体的尺寸以适应屏幕
            //Rectangle screenRectangle = Screen.PrimaryScreen.WorkingArea;
            //this.ClientSize = new Size(screenRectangle.Width, screenRectangle.Height);

            SizeChanged += MainForm_SizeChanged;
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
           
        }

       

        private void BindDisplayDevice()
        {
            //获取当前所有显示器

            var screens = Screen.AllScreens;
            //若当前只有一块显示器
            if (Screen.AllScreens.Length < 2)
                return;
            //0主显示器（系统默认，可设置哪块显示器为主显示器）1扩展显示器
            this.Location = new Point(screens[1].Bounds.Left, screens[1].Bounds.Top);
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
           
            BindDisplayDevice();
            this.WindowState = FormWindowState.Maximized;


            List<LanguageDefine> langs = new List<LanguageDefine>();
            langs.Add(new LanguageDefine("zh-cn", "Chinese"));
            langs.Add(new LanguageDefine("en", "English"));
            cboLanguages.Items.AddRange(langs.ToArray());

            cboLanguages.List = true;
            cboLanguages.SelectedValueChanged += CboLanguages_SelectedValueChanged; ;
            var lang = Configs.GetValue("Lang");
            cboLanguages.SelectedIndex = langs.FindIndex(a => a.Key == lang);

            this.Icon = ImageToIcon(windowBar1.Icon);
            this.Dark = true;
            this.Mode = AntdUI.TAMode.Dark;
            if (Dark)
            {
                AntdUI.Config.Mode = AntdUI.TMode.Dark;
                AntdUI.Config.IsDark = true;
                btnFullScreen.IconSvg = "<svg t=\"1732877456956\" class=\"icon\" viewBox=\"0 0 1024 1024\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" p-id=\"5945\" width=\"200\" height=\"200\"><path d=\"M874.666667 117.333333a32 32 0 0 1 32 32v170.666667a10.666667 10.666667 0 0 1-10.666667 10.666667h-42.666667a10.666667 10.666667 0 0 1-10.666666-10.666667V181.333333h-149.333334v-64h181.333334z m32 586.666667v170.666667a32 32 0 0 1-32 32h-181.333334v-64h149.333334V704a10.666667 10.666667 0 0 1 10.666666-10.666667h42.666667a10.666667 10.666667 0 0 1 10.666667 10.666667z m-725.333334 0v138.666667h149.333334v64H149.333333a32 32 0 0 1-32-32v-170.666667a10.666667 10.666667 0 0 1 10.666667-10.666667h42.666667a10.666667 10.666667 0 0 1 10.666666 10.666667z m149.333334-586.666667v64h-149.333334V320a10.666667 10.666667 0 0 1-10.666666 10.666667H128a10.666667 10.666667 0 0 1-10.666667-10.666667v-170.666667a32 32 0 0 1 32-32h181.333334z\" fill=\"#ffffff\" p-id=\"5946\"></path></svg>";
                this.BackColor = Color.Black;
                this.ForeColor = Color.White;
            }
            else
            {
                AntdUI.Config.Mode = AntdUI.TMode.Light;
                AntdUI.Config.IsLight = true;
                btnFullScreen.IconSvg = "<svg t=\"1732877456956\" class=\"icon\" viewBox=\"0 0 1024 1024\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" p-id=\"5945\" width=\"200\" height=\"200\"><path d=\"M874.666667 117.333333a32 32 0 0 1 32 32v170.666667a10.666667 10.666667 0 0 1-10.666667 10.666667h-42.666667a10.666667 10.666667 0 0 1-10.666666-10.666667V181.333333h-149.333334v-64h181.333334z m32 586.666667v170.666667a32 32 0 0 1-32 32h-181.333334v-64h149.333334V704a10.666667 10.666667 0 0 1 10.666666-10.666667h42.666667a10.666667 10.666667 0 0 1 10.666667 10.666667z m-725.333334 0v138.666667h149.333334v64H149.333333a32 32 0 0 1-32-32v-170.666667a10.666667 10.666667 0 0 1 10.666667-10.666667h42.666667a10.666667 10.666667 0 0 1 10.666666 10.666667z m149.333334-586.666667v64h-149.333334V320a10.666667 10.666667 0 0 1-10.666666 10.666667H128a10.666667 10.666667 0 0 1-10.666667-10.666667v-170.666667a32 32 0 0 1 32-32h181.333334z\" fill=\"#2c2c2c\" p-id=\"5946\"></path></svg>";

                BackColor = Color.White;
                ForeColor = Color.Black;
            }

            AntdUI.Config.SetCorrectionTextRendering("Microsoft YaHei UI", "宋体");

            this.lblNGCount.ForeColor = Color.Red;
            this.lblOkCount.ForeColor = ColorTranslator.FromHtml("#AEE3FF");


            //richTextBox1.BackColor = BackColor;
            ////richTextBox1.ForeColor = ForeColor;
            //richTextBox1.ReadOnly = true;
            //richTextBox1.BorderActive = null;
            //richTextBox1.BorderWidth = 0f;
            //richTextBox1.BorderHover = null;


            Refresh();

            Task.Run(() =>
            {

                //for (int i = 0; i < 50; i++)
                //{
                //    Thread.Sleep(50);
                //    AddLog($"启动成功 {i}");
                //}

                var app = InternalApp.App;
                var url = app.Urls.First();
                var u = new Uri(url);
                url = $"{u.Scheme}://localhost:{u.Port}/";
                //ShowLog($"启动成功");
                //ShowLog($"当前服务地址{u}");


            });
            Task.Run(StartInterval);




            


            Task.Run(StartSwitchPanel);
        }

        /// <summary>
        /// 多语言切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CboLanguages_SelectedValueChanged(object sender, ObjectNEventArgs e)
        {
            var v = e.Value as LanguageDefine;
            ApplyLanguage(v.Key);
        }

        private void ApplyLanguage(string lang)
        {
            var configBuilder = new ConfigurationBuilder()
               .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "i18n")) // 设置配置文件所在目录
               .AddJsonFile($"{lang}.json", optional: true, reloadOnChange: true).Build(); // 加载配置文件


            this.Text = configBuilder["main:title"];
            windowBar1.Text = Text;
            windowBar1.SubText = configBuilder["main:subTitle"];
            lbltotalOkCount.Text = configBuilder["main:totalOkCount"];
            lbltotalNgCount.Text = configBuilder["main:totalNgCount"];

            plcTable.UpdateLanguage(configBuilder);






            //topDownTextPanel1.Title = configBuilder["main:title1"];
            //topDownTextPanel2.Title = configBuilder["main:title2"];
            //topDownTextPanel3.Title = configBuilder["main:title3"];


            Configs.SetValue("Lang", lang);
            gridPanel1.Focus();

            configBuilder = null;
        }

        private void StartInterval()
        {
            try
            {
                while (this.IsHandleCreated)
                {
                    var onlineIds = App.GetOnlinePlcs();
                    plcTable.UpdateState(onlineIds);
                    Thread.Sleep(500);
                }
            }
            catch (Exception)
            {

            }
        }


        ManualResetEvent resetSwitchPanel = new ManualResetEvent(false);
        /// <summary>
        /// 动态切换显示
        /// </summary>
        private async void StartSwitchPanel()
        {
            try
            {


                while (this.IsHandleCreated)
                {
                    resetSwitchPanel.Reset();
                    resetSwitchPanel.WaitOne(5000);
                    await Task.Delay(100);
                    //await Task.Run(PlaySwitchPanelAnimation);


                }
            }
            catch (Exception)
            {

            }
        }


        List<CarouselPanel> carouselPanels = new List<CarouselPanel>();
        int CurrentPlayIndex = 0;
        int StartLeft = 0;
        /// <summary>
        ///播放切换panel的动画
        /// </summary>
        private void PlaySwitchPanelAnimation()
        {
            try
            {

                var current = carouselPanels[CurrentPlayIndex];
                var nextindex = CurrentPlayIndex + 1 >= carouselPanels.Count ? 0 : CurrentPlayIndex + 1;
                var next = carouselPanels[nextindex];
                StartLeft = current.Left;
                var initleft = current.Left + current.Width;
                this.Invoke(new Action(() =>
                {
                    next.BringToFront();
                    next.Location = new Point(initleft, current.Top); //移动位置
                    next.Size = current.Size;  //设置大小
                    next.Show();


                }));

                var sizepeed = current.Width / 3000;
                sizepeed = sizepeed <= 0 ? 1 : sizepeed;

                for (int i = 0; i < 20000; i++)
                {

                    if (i < 10)
                        sizepeed = 2;
                    else if (i < 20)
                        sizepeed = 5;
                    else if (i < 30)
                        sizepeed = 10;
                    else if (i < 40)
                        sizepeed = 30;
                    else
                        sizepeed = 100;


                    this.Invoke(new Action(() =>
                    {
                        next.Visible = true;
                        next.Width = current.Width;
                        next.Height = current.Height;
                        current.Location = new Point(current.Left - sizepeed, current.Top);
                        next.Location = new Point(next.Left - sizepeed, next.Top);
                    }));
                    if (current.Width - (Math.Abs(current.Left)) < 20)
                        break;
                    Thread.Sleep(10);
                }

                CurrentPlayIndex = nextindex;
                this.Invoke(new Action(() =>
                {

                    next.Location = new Point(StartLeft, next.Top);
                    next.Width = current.Width;
                    next.Height = current.Height;
                    current.Hide();

                }));
            }
            catch (Exception)
            {

            }
        }



        public Icon ImageToIcon(Image image)
        {
            // 创建一个与原始图像大小相同的空白图像
            Bitmap iconBitmap = new Bitmap(64, 64);
            // 使用原始图像绘制空白图像
            using (Graphics graphics = Graphics.FromImage(iconBitmap))
            {
                graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
                graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                graphics.DrawImage(image, 0, 0, 64, 64);
            }
            using (Icon icon = Icon.FromHandle(iconBitmap.GetHicon()))
            {
                // 复制Icon，因为GetHicon()在调用后会释放图标资源
                return Icon.FromHandle(icon.Handle);
            }

        }


        List<string> logStrings = new List<string>();

        /// <summary>
        /// 显示的日志队列
        /// </summary>
        ConcurrentQueue<string> logQueues = new ConcurrentQueue<string>();


        /// <summary>
        /// 最大化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFullScreen_Click(object sender, EventArgs e)
        {

        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            resetSwitchPanel.Set();

        }

        private void plcTable_Load(object sender, EventArgs e)
        {

        }
    }
}
